package data

import (
	"database/sql"

	"sieve_admin_server_userpass/pkg/config"
	"sieve_admin_server_userpass/pkg/im3/db"
)

var fCorpName = config.String("corp.name", "搜虎网络", "corporation name")

func GetCorpName() string {
	return *fCorpName
}

type GroupData struct {
	Gid   int
	Owner int
	Name  string
	Pwd   string
	Uids  []int
}

func (g *GroupData) Copy() *GroupData {
	ret := &GroupData{}
	*ret = *g
	return ret
}

func GetGroupByGid(gid int) (*GroupData, error) {
	data := &GroupData{Gid: gid, Uids: []int{}}
	if err := db.Mysql().QueryRow("SELECT `Owner`,`Name` FROM `Group` WHERE `Gid`=?", gid).Scan(
		&data.Owner,
		&data.Name,
	); err != nil {
		return nil, err
	}

	rows, err := db.Mysql().Query("SELECT `Uid` FROM `UserGroup` WHERE `Gid`=? ORDER BY `id`", gid)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	for rows.Next() {
		var uid int
		if err := rows.Scan(&uid); err != nil {
			return nil, err
		}
		data.Uids = append(data.Uids, uid)
	}

	return data, nil
}

/*
	func GetGroupName(gid int) (string, error) {
		if gid == 0 {
			return *fCorpName, nil
		}
		name := ""
		err := db.Mysql().QueryRow("SELECT `Name` FROM `Group` WHERE `Gid`=?", gid).Scan(&name)
		return name, err
	}
*/
func GetUserGroupName(uid, gid int) (name string, err error) {
	if gid == 0 {
		name = GetUserCompanyName(uid)
		if name == "" {
			err = sql.ErrNoRows
		}
		return
	}
	err = db.Mysql().QueryRow("SELECT `Name` FROM `Group` WHERE `Gid`=?", gid).Scan(&name)
	return
}

func GetGroupUids(gid int) ([]int, error) {
	rows, err := db.Mysql().Query("SELECT `Uid` FROM `UserGroup` WHERE `Gid`=?", gid)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	uids := []int{}
	for rows.Next() {
		var uid int
		if err := rows.Scan(&uid); err != nil {
			return nil, err
		}
		uids = append(uids, uid)
	}
	return uids, nil
}

func GetUnitUids(unit int) ([]int, error) {
	rows, err := db.Mysql().Query("SELECT `Uid` FROM `UserUnit` WHERE `Unit`=?", unit)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	uids := []int{}
	for rows.Next() {
		var uid int
		if err := rows.Scan(&uid); err != nil {
			return nil, err
		}
		uids = append(uids, uid)
	}
	return uids, nil
}

func IsUserInGroup(uid, gid int) bool {
	if gid == 0 {
		return GetUserCompanyId(uid) > 0
	}
	var id int
	if err := db.Mysql().QueryRow("SELECT `id` FROM `UserGroup` WHERE `Uid`=? AND `Gid`=?", uid, gid).Scan(&id); err != nil {
		return false
	}
	return id > 0
}

func IsUserInUnit(uid, unit int) bool {
	if unit == 0 {
		return GetUserCompanyId(uid) > 0
	}
	var id int
	if err := db.Mysql().QueryRow("SELECT `id` FROM `UserUnit` WHERE `Uid`=? AND `Unit`=?", uid, unit).Scan(&id); err != nil {
		return false
	}
	return id > 0
}

func IsUserGroupOwner(uid, gid int) bool {
	var guid int
	if err := db.Mysql().QueryRow("SELECT `Owner` FROM `Group` WHERE Gid=?", gid).Scan(&guid); err != nil {
		return false
	}
	return uid == guid
}
